<template>
  <div class="add-bank">
    <div style="position: relative;width:100%;height:50px;">
      <van-nav-bar
        title="添加储蓄卡"
        fixed
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
    <van-cell-group class="from-add">
      <van-field
        type="text"
        v-model="bankCardID"
        label="银行卡号"
        icon="scan"
        placeholder="请输入常用的储蓄卡卡号"
        @keyup="bankKey"
        @blur="blurChange"
        @click-icon="icoclick('scan')"
      >
      <!--  -->
        <van-icon slot="icon"  class-prefix="my-icon" name="scan" />
      </van-field>
      <van-field
        type="number"
        v-model="phoneValue"
        label="预留手机号"
        icon="info-o"
        placeholder="请输入预留手机号"
        @keyup="phoneKey"
        @click-icon="icoclick('info-o')"
      />
       <van-field
        type="number"
        v-model="smsCode"
        center
        label="短信验证码"
        placeholder="请输入短信验证码"
      >
        <van-button slot="button" size="small" style="border:none;color:#6699CC;" @click="SendClick" v-if="sendAuthCode">获取验证码</van-button>
        <van-button slot="button" size="small" style="border:none"  v-if="!sendAuthCode">{{auth_time}}s 后重新获取</van-button>
      </van-field>
    </van-cell-group>
    <van-button class="btn"
          :disabled="!(phoneValue&smsCode)"
          round size="normal"
          @click="btnClick">提交</van-button>
    <div class="hint-bank" @click="supportBank">查看支持银行</div>
    <van-popup class="bankList" v-model="bankShow">
        <div class="title">支持银行 <span @click="popupClear">X</span></div>
      <van-row gutter="10" style="margin-top:55px;">
        <van-col class="bank-item" span="8" v-for="item in bankLists"
        :key="item.id">
          <van-col span="14" offset="5"><img :src="item.icon" alt=""></van-col>
          <van-col span="24" style="margin-top:10px;font-size:13px;color:#666;">{{item.name}}</van-col>
        </van-col>
      </van-row>
    </van-popup>
  </div>
</template>

<script>
// import bankCardAttribution from '../../utils/bankCardType.js'
import bankCardAttribution from "../../utils/bankCardType";
// var bankCardAttribution = require('../../utils/bankCardType.js');
import { Field, CellGroup, Button,Icon, Popup,Row, Col, Toast, Dialog,NavBar } from 'vant';
export default {
  components:{
    [Field.name]:Field,
    [CellGroup.name]:CellGroup,
    [Button.name]:Button,
    [Icon.name]:Icon,
    [Popup.name]:Popup,
    [Row.name]:Row,
    [Col.name]:Col,
    [Toast.name]:Toast,
    [Dialog.name]:Dialog,
    [NavBar.name]:NavBar,
  },
  data(){
    return{
      smsState:false,
      bankCardID:'',
      phoneValue:'',
      smsCode:'',
      bankShow:false,//显示银行
      bankLists:'',
      token:'',
      info:'',
      bank:'',
      sendAuthCode:true,//短信btn状态
      auth_time:60,//秒
    }
  },
  mounted(){
    _hmt.push(['_trackPageview', '/add-bankCard']);
    this.$util.goBack();
    Toast.loading({duration:1000,mask: false,message: '加载中...'});

    let _this = this;

    window.onBankCard=(msg)=>{
      if(msg){
        let data=JSON.parse(msg);
        _this.bankCardID = data.bankCardNumber;
      }
    }
    // 获取本地数据
    this.$util.getUser().then(token=>{
       _this.token=token;
      if(token!='-1'){
        _this.myInfo(token);
        _this.bankList(token);
      }
    })
  },
  methods:{

    onClickLeft(){
      this.$util.url('/loanApplication','申请借款')
    },
    bankKey(e){
      // "a b c".replaceAll(" ","");
      let phoneNum = this.bankCardID.trim();
      this.bankCardID =phoneNum.replace(/\s/g,'').replace(/[^\d]/g,'').replace(/(\d{4})(?=\d)/g,'$1 ');
    },
    blurChange(){
      // 6217001210024455220
      let bankId =  this.bankCardID.replace(/\s+/g,"");
      console.log(bankId)
      let bank=bankCardAttribution(bankId);
      console.log(bank)
      if(bank == 'error'){
        bank = '';
      }

      this.bank = bank;
    },
    phoneKey(){
      console.log(this.phoneValue)
      if(this.phoneValue.length>=11){
        this.phoneValue = this.phoneValue.substring(0,11)
      }
    },
    // myinfo
    myInfo(token){
      let _this = this;
      this.$api.post('/user/v1/info',{},s=>{
        console.log(s);
        _this.info = s.module;
        _this.phoneValue = s.module.phone

      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
            _this.$util.url('/HomeBefore','首页')
          }else{
            Toast(f.errorMessage);
          }
      },{
        'Accept': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':token
      })
    },
    // 银行列表
    bankList(){
      let _this = this;
      this.$api.get('/bank/v1/list?bankrollCode='+this.$util.bankrollCode,{},s=>{
        console.log(s)
        _this.bankLists = s.module;
      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
          _this.$util.url('/HomeBefore','首页')
        }else{
          Toast(f.errorMessage);
        }
      },{
        'Content-Type': 'application/json',
        'Accept': "*/*",
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':this.token
      })
    },
    icoclick(e){
      let  html= `<div>银行预留手机号是办理该银行卡时所填写的手机号码。</div>
      <div>没有预留手机号忘记或者已停用，请联系银行客服更新处理</div>`;
      console.log(e)
      if(e =='scan'){
        window.control.getOnBankCard()
      }else{
        Dialog.alert({
          title: '手机号说明',
          message: html,
          confirmButtonText:'我知道了',
        }).then(() => {

        }).catch(() => {
          // on cancel
        });
      }

    },
    // 下一步
    btnClick(){
      //
      let _this = this;
      if(!this.smsState){
        Toast('请先获取短信验证码!');
        return false
      }

      this.$api.post('/borrowing/v1/bindCard?bankrollCode='+this.$util.bankrollCode+'&smsCode='+this.smsCode,{},s=>{
        console.log(s);
        const toast = Toast.loading({
          duration: 0,       // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          loadingType: 'spinner',
          message:`绑定成功 3秒`
        });

        let second = 3;
        const timer = setInterval(() => {
          second--;
          if (second) {
            toast.message = `绑定成功 ${second}秒`;
          } else {
            this.$util.url('/loanApplication','申请借款')
            clearInterval(timer);
            Toast.clear();
          }
        }, 1000);
      },f=>{
        if(f.resultCode=='10000'||f.resultCode=='10003'||f.resultCode=='10001'||f.resultCode=='10002'){
          _this.$util.url('/HomeBefore','首页')
        }else{
          Toast(f.errorMessage);
        }
      },{
        'Accept': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':this.token
      })
    },
    // 发送验证码
    SendClick(){
      let _this = this;
      let bankId =  this.bankCardID.replace(/\s+/g,"");
      let pat = /^1\d{10}$/;
      if(!this.phoneValue){
        Toast('请输入手机号');
        return false
      }
      if(!pat.test(this.phoneValue)){
        Toast('请输入有效的手机号码');
        return false
      }
      Toast.loading({message: '加载中...'});
      this.$api.post('/borrowing/v1/bindCardSendConfirmSMS?bankrollCode='+this.$util.bankrollCode+'&cardNumber='+bankId+'&mobilePhone='+this.phoneValue+'&bankName=',{},s=>{
        _this.smsState=true;
          Toast.clear();
          _this.sendAuthCode = false;
          _this.auth_time = 60;
          var auth_timetimer =  setInterval(()=>{
              _this.auth_time--;
              if(_this.auth_time<=0){
                  _this.sendAuthCode = true;
                  clearInterval(auth_timetimer);
              }
          }, 1000);
        },f=>{
        Toast(f.errorMessage);
      },{
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'channelCode':this.$util.channelCode,
        'version':this.$util.version,
        'token':this.token
      })
    },
    popupClear(){
      this.bankShow=false;
    },
    supportBank(){
      this.bankShow=true;

      // console.log(1233)
    },
  }
}
</script>


<style scoped >
  /***
  * 产品主题颜色需求
  * #FF8024 按钮 突出文字 ico
  * #FFD500 B辅助色
  * #FFEC9C c辅助色
  * #1D0F00 重要文字
  * #41424E 副标题段落
  * #797A79 次要文字
  * #A9AAA9 不可点击
  * #E6E6E6 分割线 描边
  * #F6F7F6 背景
  * #6699CC 链接
  */
.add-bank{
  width:100%;
  height:100%;
  background: #F6F7F6;
}
.from-add{
  margin-top:10px;
}
.btn{
  width:80%;
  margin-top:50px;
  background:#FF8024;
  color:#fff;
}
.hint-bank{
  margin-top:30px;
  font-size:14px;
}
.bankList{
  position:absolute;
  width:80%;
  height:50%;
  margin-left:-40%;
  margin-top:-40%;
  /* min-height:20%; */
  overflow: hidden;
  border-radius: 10px;
  overflow-y:scroll;
  -webkit-overflow-scrolling: touch;
  transform:none;
}
.bankList .title{
  position: fixed;
  /* top:0; */
  width:80%;
  height:50px;

  text-align: center;
  font-size:16px;
  line-height: 50px;
  background: #fff;
  color:#333;
}
.title span{
  position: absolute;
  top:0px;
  right:15px;
  color:#797A79;
}
.bank-item{

  height:90px;
}
.bank-item img{
  width:100%;
}
</style>